package com.example.demo.controller;

import com.example.demo.api.JsonResult;
import com.example.demo.api.ResultCode;
import com.example.demo.entity.Reservation;
import com.example.demo.entity.Stadium;
import com.example.demo.entity.User;
//import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import com.example.demo.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1")
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    private UserService userservice;
//    @Autowired
//    private TokenService tokenservice;

//    JsonResult r = new JsonResult();

    /**
     * 登录
     * @param user
     * @return
     */
    @PostMapping("/user/token")
    public JsonResult login(@RequestBody User user){

        System.out.println("......登录......");
        try {
            User temp = userservice.findAUsers(user.getUsername());
            //System.out.println(temp);
            if(temp.getPassword().equals(user.getPassword())) {
                if(temp.isAdmin()) {/**管理员登录**/
                    User user1=userservice.findUserId(user);
                    String token= TokenUtil.generateToken(user1);
//                    String token = tokenservice.createToken();
//                    tokenservice.putToken(user.getUsername(), token);
                    System.out.println("管理员登录成功\n");
                    return JsonResult.result(ResultCode.A_LOGIN_SUCCESS.getCode(), ResultCode.A_LOGIN_SUCCESS.getMessage(), token);
                } else {/**普通用户登录**/
                    User user1=userservice.findUserId(user);
                    String token= TokenUtil.generateToken(user1);
//                    String token = tokenservice.createToken();
//                    tokenservice.putToken(user.getUsername(), token);
                    System.out.println("登录成功\n");
                    return  JsonResult.result(ResultCode.U_LOGIN_SUCCESS.getCode(), ResultCode.U_LOGIN_SUCCESS.getMessage(), token);
                }
            } else{/**密码错误**/
                System.out.println("密码错误\n");
                return JsonResult.result(ResultCode.PASSWORD_FAILED.getCode(), ResultCode.PASSWORD_FAILED.getMessage());
            }
        } catch(NullPointerException e) {/**用户不存在**/
            System.out.println("用户不存在\n");
            return JsonResult.result(ResultCode.USERNAME_FAILED.getCode(), ResultCode.USERNAME_FAILED.getMessage());
        } catch (Exception e){
            System.out.println(e.toString()+"\n登陆失败\n");
            return JsonResult.result(ResultCode.LOGIN_FAILED.getCode(), ResultCode.LOGIN_FAILED.getMessage());}

    }


    /**
     * 退出登录
     * @return
     */
    @DeleteMapping("/user/token")
    public JsonResult logout() {
//        System.out.println("token: "+token+" , username"+tokenservice.getName(token)+" 退出......");
        try {
            /**退出成功**/
            System.out.println("退出成功\n");
            return JsonResult.result(ResultCode.LOGOUT_SUCCESS.getCode(), ResultCode.LOGOUT_SUCCESS.getMessage());

        } catch (Exception e) {/**退出失败**/
            System.out.println(e.toString()+"\n退出失败\n");
            return JsonResult.result(ResultCode.LOGOUT_FAILED.getCode(), ResultCode.LOGOUT_FAILED.getMessage());
        }
    }

    /**
     * 查看场地
     * @return
     */
    @GetMapping("/user/stadiums/{type}")
    public JsonResult browse (@PathVariable(name="type") String type) {
        System.out.println("......浏览场地......");
        List<Stadium> stadiumList;
        try {
            stadiumList = userservice.findStadiumsByType(type);
            System.out.println(stadiumList.toString());
            System.out.println("查看成功\n");
            return JsonResult.result(ResultCode.GET_INFO_SUCCESS.getCode(), ResultCode.GET_INFO_SUCCESS.getMessage(), stadiumList);

        } catch (Exception e) {
            System.out.println(e);
            System.out.println("查看失败\n");
            return JsonResult.result(ResultCode.GET_INFO_FAILED.getCode(), ResultCode.GET_INFO_FAILED.getMessage());
        }
    }

    /**
     * 预定场地
     * @return
     */
    @PostMapping("/user/reservations")
    public JsonResult reserve (@RequestBody Reservation reservation) {
        System.out.println("......预定场地......");
        System.out.println("预定信息："+reservation);
        try {
            if(userservice.findReservationId(reservation)==0) {
                userservice.reserveStadiums(reservation);
                System.out.println("预定成功\n");
                System.out.println("返回信息:"+JsonResult.result(ResultCode.ADD_RESERVATION_SUCCESS.getCode(), ResultCode.ADD_RESERVATION_SUCCESS.getMessage()).toString());
                return JsonResult.result(ResultCode.ADD_RESERVATION_SUCCESS.getCode(), ResultCode.ADD_RESERVATION_SUCCESS.getMessage());
            } else {
                System.out.println("该时间已被预订\n");
                return JsonResult.result(ResultCode.RESERVATION_FAILED.getCode(), ResultCode.RESERVATION_FAILED.getMessage());
            }

        } catch (Exception e) {
            System.out.println(e);
            System.out.println("预定失败\n");
            return JsonResult.result(ResultCode.ADD_RESERVATION_FAILED.getCode(), ResultCode.ADD_RESERVATION_FAILED.getMessage());
        }
    }

    /**
     * 查看预定记录
     * @param username
     * @return
     */
    @GetMapping("/user/myreservations/{username}")
    public JsonResult browseItem (@PathVariable(name="username") String username) {
        System.out.println("......查看预定记录......");
        List<Reservation> reservationList;
        try {
            reservationList = userservice.findReservationsByUsername(username);
            System.out.println(reservationList.toString());
            System.out.println("查看成功\n");
            return JsonResult.result(ResultCode.GET_INFO_SUCCESS.getCode(), ResultCode.GET_INFO_SUCCESS.getMessage(), reservationList);
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("查看失败\n");
            return JsonResult.result(ResultCode.GET_INFO_FAILED.getCode(), ResultCode.GET_INFO_FAILED.getMessage());
        }
    }

    //取消预订
    @DeleteMapping("/user/reservations/{username}/{r_id}")
    public JsonResult deleteInfo(@PathVariable(name="r_id") String r_id,
                                   @PathVariable(name="username") String username) {
        System.out.println("......取消预订......");
        System.out.println(username);
        try {
            int id = Integer.parseInt(r_id);
            if(userservice.findUserByrid(id).equals(username)) {
                userservice.deleteReservation(id);
                System.out.println("取消成功\n");
                return JsonResult.result(ResultCode.CANCEL_SUCCESS.getCode(), ResultCode.CANCEL_SUCCESS.getMessage());
            } else {
                System.out.println("权限不足\n");
                return JsonResult.result(ResultCode.TOKEN_FAILED.getCode(), ResultCode.TOKEN_FAILED.getMessage());
            }
        } catch (Exception e) {
            System.out.println(e);
            System.out.println("取消\n");
            return JsonResult.result(ResultCode.CANCEL_FAILED.getCode(), ResultCode.CANCEL_FAILED.getMessage());
        }
    }


    /**
     * 修改密码
     * @param user
     * @return
     */
    @PutMapping("/user")
    public JsonResult changePWD(@RequestBody User user){
        System.out.println("......修改密码.....");
        try {
            userservice.changePWD(user.getUsername(), user.getPassword());
            System.out.println("修改成功\n");
            return JsonResult.result(ResultCode.PUT_INFO_SUCCESS.getCode(), ResultCode.PUT_INFO_SUCCESS.getMessage());

        } catch (Exception e) {
            System.out.println(e.toString()+"\n修改失败\n");
            return JsonResult.result(ResultCode.PUT_INFO_FAILED.getCode(), ResultCode.PUT_INFO_FAILED.getMessage());
        }
    }


}
